'''
处理的公共函数
VER 8.28
'''
import sys
import uuid
import logging
import logging.config
import shutil
import urllib.request
import os
import time
import subprocess
import hashlib
from datetime import datetime  
import ffprobe
import setting
import zipfile
import json
import jieba
import jieba.posseg as pseg
from urllib.parse import urlparse  
from pymediainfo import MediaInfo
from pydub import AudioSegment
import numpy as np

h264_decoder = "h264_cuvid"
hevc_decoder = "hevc_cuvid"
h264_encoder = "nvenc_h264"
GPU_AVAILABLE = os.environ.get('GPU_AVAILABLE')

from configparser import ConfigParser

def getWorkDir():
    path = os.path.dirname(os.path.abspath(__file__))
    return path
def getLogger():
    logging.config.fileConfig(f"{getWorkDir()}/config/log.conf", defaults=None, disable_existing_loggers=True)
    return logging.getLogger('simpleLog')

logger = getLogger()

# 获取生成的UUID做为服务的标识
def getsUUID():
    return str(uuid.uuid1())

#  获取文件名称,带后缀
def getFileName(file):
    is_Http = True if file[:4].lower() == "http" else False
    if is_Http:
        result = urlparse(file)  
  
        # 使用os.path.basename从URL的路径部分获取文件名  
        filename = os.path.basename(result.path)  
    else:
        filename = os.path.basename(file) 
    if filename == None:
        filename = getMD5(file)
    return filename


#  从内网下载文件到本地，或者拷贝文件到本地
def download(source, target):
    is_Http = True if source[:4].lower() == "http" else False
    if is_Http:
        for i in range(5):
            try:
                # logger = getLogger()
                rurl = source.replace(" ", "").replace("\n", "").replace("\r", "")
                result = urllib.request.urlretrieve(rurl, target, reporthook=report)
                return True
            except Exception as e:
                print(e)
                time.sleep(1)
        return False
    else:
        shutil.copy(source, target)

def report(count, blockSize, totalSize):
    percent = int(count*blockSize*100/totalSize)
    sys.stdout.write("\r正在下载文件:%d%%" % percent + ' complete')
    sys.stdout.flush()

# 获取字符串的md5
def getMD5(str):
    md5_str = hashlib.md5(str.encode()).hexdigest().upper()
    return md5_str

def fileIsExit(filename):
    if (not os.path.exists(filename)):
        logger.debug(f"file[{filename}] not exit!")
        return False
    return True

def PathIsExit(path):
    return(fileIsExit(path)) 

def havePath(path):
    if(fileIsExit(path)):
        return
    else:
        os.makedirs(path)

# 判断文件是否为视频,因为网络文件，有时下载会出问题
def getDurationAndResolution(video):
    try:
        if(not fileIsExit(video)):
            return 0
        media_info = MediaInfo.parse(video)
        for track in media_info.tracks:
            if track.track_type == "Video":
                jdata = track.to_data()
                duration = round(float(jdata["duration"])/1000)
                resolution = f"{track.width}x{track.height}"
                return duration, resolution
        return 0, None
    except Exception as e:
        return 0, None

# 把音频分离出来
def extractAudio(audio, taudio):
    try:
        shellcmd = ["ffmpeg", "-y", "-i", f"{audio}", "-vn", "-c:a", "mp3", "-ar", "16000", "-f", "mp3", taudio]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("音频抽取失败["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

# 获取音频Wav文件的响度值, 生成的是响度值json数据,100ms一片，每少产生10个切片
def getWavLoudness(wav_file, target, chunk_size_ms=100):

    audio_file = wav_file
    # 读取音频文件
    audio = AudioSegment.from_file(audio_file)
    
    # 将音频切成10ms的片段
    chunks = list(audio[::chunk_size_ms])

    # 提取每个片段的响度和时间戳
    loudness_data = []
    for i, chunk in enumerate(chunks):
        # 获取每个片段的RMS值
        rms = chunk.rms
        # 计算响度（分贝）
        loudness = 20 * np.log10(rms)
        if loudness == float('inf') or loudness == float('-inf'):
            loudness = 0

        # 计算时间戳
        timestamp = i * chunk_size_ms/1000.0  # 转换为秒
        # 保存时间戳和响度值
        loudness_data.append({"timestamp": round(timestamp, 3), "loudness": round(loudness, 2)})


    # 打印结果
    with open(target, "w+", encoding='utf-8') as file:
        json.dump(loudness_data, file)

    return

# 获取视频的编码
def getVideoCodec(filename):
    try:
        probe = ffprobe.FFProbe(filename)
        video = probe.video[0]
        codec = video.codec_name
        if(codec == 'hevc' or  ('265' in codec)):
            return '265'
        if('264' in codec):
            return '264'
        return None
    except Exception as e:
        return None
# 把视频转成360p
def vTo360p(video, tvideo=""):
    try:
        if tvideo == "":
            tvideo = f"{video}_360p.mp4"
        shellcmd = ["ffmpeg", "-y", "-i", video, "-vcodec", "h264", "-vf", "scale=-2:360", "-r", "25", "-crf", "25", "-acodec", "aac", "-f", "mp4", tvideo]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("视频转成360p错误["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

def getFileName(filename):
    file_name = os.path.basename(filename)
    file_name1 = os.path.splitext(file_name)[0]
    return file_name1

def getPath(filename):
    file_name = os.path.dirname(filename)
    return file_name

# 把视频转成360和1080, 在video相同的目录上生成
def  to360And1080(video):
    try:
        # 是否有GPU参与工作
        usedevice = ""
        codec = getVideoCodec(video)
        fileName = getFileName(video)
        path = getPath(video)
        t1080p = f"{path}/video_1080p.mp4"
        t360p = f"{path}/video_360p.mp4"
        if(GPU_AVAILABLE == 'YES' and codec == '264'):
            shellcmd = ["ffmpeg", "-hwaccel", "cuvid", "-c:v", "h264_cuvid", "-y", "-i", video, "-c:v", "h264_nvenc", "-vf", "scale_npp=-2:1080", "-b:v", "1500k", "-r", "25", "-crf", "21", "-c:a", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", t1080p, "-c:v", "h264_nvenc", "-vf", "scale_npp=-2:360", "-b:v", "350k", "-r", "25", "-crf", "22",  "-c:a", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", t360p]
        elif(GPU_AVAILABLE == 'YES' and codec == '265'):
            shellcmd = ["ffmpeg", "-hwaccel", "cuvid", "-c:v", "hevc_cuvid", "-y", "-i", video, "-c:v", "h264_nvenc", "-vf", "scale_npp=-2:1080", "-b:v", "1500k", "-r", "25", "-crf", "21", "-c:a", "aac", "-max_muxing_queue_size", "1024","-movflags", "faststart", "-f", "mp4", t1080p, "-c:v", "h264_nvenc", "-vf", "scale_npp=-2:360", "-b:v", "350k", "-r", "25", "-crf", "22",  "-c:a", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", t360p]
        else:
            shellcmd = ["ffmpeg", "-y", "-i", video, "-vcodec", "h264", "-vf", "scale=-2:1080", "-r", "25", "-crf", "21", "-b:v", "1500k", "-acodec", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", t1080p, "-vcodec", "h264", "-vf", "scale=-2:360", "-b:v", "350k", "-r", "25", "-crf", "21", "-acodec", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", t360p]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("视频转成1080和360错误["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

# 把视频转成1080p并加字幕
def tr1080pAddSubtitle(source, subtitle, target):

    PrimaryColour = "0xFFFFFF"
    OutlineColour = "0x000000"
    # 宽度都为1080，高度自适应

    fontsize = 26
    try:
        # 是否有GPU参与工作, 使用GPU进行加字幕，不能够进行GPU解码，需要使用CPU进行解码，否则用不了vf滤镜
        if(GPU_AVAILABLE == 'YES'):
            # shellcmd = ["ffmpeg", "-y", "-i", source, "-c:v", "h264_nvenc", "-vf", f"scale_npp=-2:1080,subtitles={subtitle}:force_style='Fontsize={fontsize},PrimaryColour={PrimaryColour},OutlineColour={OutlineColour},Outline=0.5,Alignment=2,MarginV=5'", "-b:v", "3000k", "-r", "30", "-crf", "21", "-c:a", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]
            # 目前4.2.9不支持一些参数，所以暂时先去掉
            shellcmd = ["ffmpeg", "-y", "-i", source, "-c:v", "h264_nvenc", "-vf", f"scale=-2:1080,subtitles={subtitle}:force_style='Fontsize={fontsize},Fontname=YaHei'", "-b:v", "3000k", "-r", "30", "-crf", "21", "-c:a", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]
        else:
            # shellcmd = ["ffmpeg", "-y", "-i", source, "-vf", f"scale=-2:1080,subtitles={subtitle}:force_style='Fontsize={fontsize},PrimaryColour={PrimaryColour},OutlineColour={OutlineColour},Outline=0.5,Alignment=2,MarginV=5'", "-vcodec", "h264",  "-r", "30", "-crf", "21", "-b:v", "3000k", "-acodec", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]
            shellcmd = ["ffmpeg", "-y", "-i", source, "-vf", f"scale=-2:1080,subtitles={subtitle}:force_style='Fontsize={fontsize},Fontname=YaHei'", "-vcodec", "h264",  "-r", "30", "-crf", "21", "-b:v", "3000k", "-acodec", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("视频压制字幕错误["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

# 把视频转码
def trTo1080p(source, target, brate='2000kb', fps='25'):
    try:
        # 是否有GPU参与工作
        if(GPU_AVAILABLE == 'YES'):
            cmd = ["ffmpeg", "-hwaccel", "cuvid", "-c:v", "h264_cuvid", "-y", "-i", source, "-c:v", "h264_nvenc", "-vf", 'scale_npp=-2:1080', "-b:v", f"{brate}", "-r", f"{fps}", "-crf", "21", "-c:a", "copy", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]
        else:
            cmd = ["ffmpeg", "-y", "-i", source, "-c:v", "h264", "-vf", 'scale=-2:1080', "-b:v", f"{brate}", "-r", f"{fps}", "-crf", "21", "-c:a", "copy", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]

        ret = subprocess.run(cmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("视频转码错误["+",".join(cmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

# 把视频转码
def transcode(source, target, resolution, brate, fps):

    t_target = f"{os.path.dirname(target)}/{getsUUID()}.mp4"
    try:
        _, s_resolution = getDurationAndResolution(source)
        s_width, s_height = s_resolution.split("x")
        iwidth = int(s_width)
        iheight = int(s_height)
        flag = False
        h_flag = False
        m_width, m_height = resolution.split("x")
        width, height = resolution.split("x")
        twidth = int(width)
        theight = int(height)
        # 为了保证其视频内容不被拉伸，所以需要保证其原始的分辨率的内容
        # 获取原始的宽高比
        srate = int(iwidth * 100 / iheight)
        trate = int(twidth * 100 / theight)
        # 如果分辨率与原始不等，则设置需要遮盖的要进行遮盖；
        if(srate != trate):
            flag = True
        # 如果高度大于宽度，则认为是竖屏的，则以宽度为准
        if(twidth < theight):
            h_flag = True

        shcmd = []
        # 是否有GPU参与工作
        if(GPU_AVAILABLE == 'YES'):
            if(h_flag):
                vfilter = f"scale_npp={twidth}:-2"
                # vfilter = f"scale_npp={twidth}:-2,pad={twidth}:{theight}:(ow-iw)/2:(oh-ih)/2:color=black" 
            else:
                vfilter = f"scale_npp=-2:{theight}" 
                # vfilter = f"scale_npp=-2:{theight},pad={twidth}:{theight}:(ow-iw)/2:(oh-ih)/2:color=black" 
            shellcmd1 = ["ffmpeg", "-hwaccel", "cuvid", "-c:v", "h264_cuvid", "-y", "-i", source, "-c:v", "h264_nvenc", "-vf", vfilter, "-b:v", f"{brate}", "-r", f"{fps}", "-crf", "21", "-c:a", "copy", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", t_target]
            shcmd.append(shellcmd1)
            # 如果横竖屏转换，则需要进行遮盖处理
            if(flag):
                vfilter = f"pad={twidth}:{theight}:(ow-iw)/2:(oh-ih)/2:color=black"
                shellcmd2 = ["ffmpeg", "-y", "-i", t_target, "-c:v", "h264_nvenc", "-vf", vfilter, "-b:v", f"{brate}", "-r", f"{fps}", "-crf", "21", "-c:a", "copy", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]
            else:
                shellcmd2 = ["cp", "-r", t_target, target]
            shcmd.append(shellcmd2) 
            shellcmd3 = ["rm", "-rf", t_target]
            shcmd.append(shellcmd3)
        else:
            if(h_flag):
                vfilter = f"scale=-2:{twidth},pad={twidth}:{theight}:(ow-iw)/2:(oh-ih)/2:color=black" 
            else:
                vfilter = f"scale={theight}:-2,pad={twidth}:{theight}:(ow-iw)/2:(oh-ih)/2:color=black" 
            shellcmd = ["ffmpeg", "-y", "-i", source, "-vcodec", "h264", "-vf", vfilter, "-r", f"{fps}", "-crf", "21", "-b:v", f"{brate}", "-acodec", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]
            shcmd.append(shellcmd) 
        for cmd in shcmd:
            ret = subprocess.run(cmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
            if(ret.returncode != 0):
                logger.error("视频转码错误["+",".join(cmd)+"]")
                return False
        return True
    except Exception as e:
        print(e)
        return False

def todayFmt(fmt):
    # 获取当前日期
    current_date = datetime.now().date()
    
    # 将日期格式化为 yyyymmdd 格式 '%Y%m%d'
    formatted_date = current_date.strftime(fmt)
    
    return formatted_date

def clipperVideo(source, target, start, end):
    sfmt = stimeFmtHHMMDDSSS(start)
    efmt = stimeFmtHHMMDDSSS(end)
    try:
        # 是否有GPU参与工作, 使用GPU进行加字幕，不能够进行GPU解码，需要使用CPU进行解码，否则用不了vf滤镜
        shellcmd = ["ffmpeg", "-ss", f"{sfmt}", "-to", f"{efmt}", "-accurate_seek", "-i", source, "-c:v", "h264_nvenc", "-crf", "18", "-c:a", "aac", "-max_muxing_queue_size", "1024", "-async", "5", "-movflags", "faststart", "-vbsf", "h264_mp4toannexb","-y" ,target]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("视频切割["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False
# 合成视频内容
def concatVideo(conlst, target):
    try:
        shellcmd = ["ffmpeg", "-f", "concat", "-safe", "0", "-i", conlst, "-c", "copy", target]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error(" 视频合成["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

# 合成视频内容
def addEndFrame(video):
    try:
        tvideo = video
        target = f"{video}_tmp.mp4"
        shellcmd = ["ffmpeg", "-y", "-i", video, "-c:v", "h264_nvenc", "-vf", 'tpad=stop_mode=clone:stop_duration=1', "-crf", "17", "-c:a", "copy", "-movflags", "faststart", "-f", "mp4", target]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error(" 视频合成["+",".join(shellcmd)+"]")
            return False
        shutil.move(target, tvideo)
        return True
    except Exception as e:
        print(e)
        return False

# 把音频标准化
def audioStandard1(audio, taudio):
    try:
        shellcmd = ["ffmpeg", "-y", "-i", audio, "-vn", "-ar", "32000", "-ac", "1", taudio]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("音频规范化失败["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

# 把音频标准化成8000Hz的mp3
def aTo8kHzMp3(audio, taudio):

    if taudio == "":
        taudio = f"{audio}_8k.mp3"
    try:
        shellcmd = ["ffmpeg", "-y", "-i", audio, "-vn", "-ar", "8000", "-ac", "1", "-f", "mp3", taudio]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("音频规范化mp3失败["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

# 把音频标准化
def audioStandard(audio, taudio):
    try:
        shellcmd = ["ffmpeg", "-y", "-i", audio, "-vn", taudio]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("音频规范化失败["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

# 如果判断目录存在，则删除重建
def reMkDir(path):

    if isExists := os.path.exists(path):
        shutil.rmtree(path)
    # 如果不存在则创建目录
    os.makedirs(path)

# 如果判断目录存在，则删除
def rmDir(path):

    if isExists := os.path.exists(path):
        shutil.rmtree(path)

def jsonToVtt(jdata, vttfile):

    with open(vttfile, 'w+', encoding='utf-8') as file1:
        file1.write("WEBVTT\n\n")
        for index, sub in enumerate(jdata, start=1):
            start = timeFmtHHMMDDSSS(sub["start"])
            end = timeFmtHHMMDDSSS(sub["end"])
            stime = f"{start[0]:02d}:{start[1]:02d}:{start[2]:02d}.{start[3]:03d} --> {end[0]:02d}:{end[1]:02d}:{end[2]:02d}.{end[3]:03d}\n"
            # file1.write(f"{index}\n")
            file1.write(stime)
            file1.write(f"{sub['text']}\n\n")

def mkZip(zipf, path):
    with zipfile.ZipFile(zipf, 'w', zipfile.ZIP_DEFLATED) as z:
        if os.path.isdir(path):
            for d in os.listdir(path):
                z.write(path+os.sep+d, arcname=d)
        
# 给视频加字幕(硬字幕)
def videoAddSubtitle(source, subtitle, target):

    PrimaryColour = "0xFFFFFF"
    OutlineColour = "0x000000"
    _, resolution = getDurationAndResolution(source)
    swidth, sheight = resolution.split("x")
    width = int(swidth)
    height = int(sheight)

    safeWidth = width * 0.8
    safeHeight = height * 0.8
    safeX = (width - safeWidth) / 2
    safeY = (height - safeHeight) / 2

    Font = 38
    fontsize = int((width / 1920) * Font)
    try:
        # 是否有GPU参与工作, 使用GPU进行加字幕，不能够进行GPU解码，需要使用CPU进行解码，否则用不了vf滤镜
        if(GPU_AVAILABLE == 'YES'):
            shellcmd = ["ffmpeg", "-y", "-i", source, "-vf", f"subtitles={subtitle}:force_style='Fontsize={fontsize},PrimaryColour={PrimaryColour},OutlineColour={OutlineColour},Outline=0.5,Alignment=2,MarginV=5'", "-c:v", "h264_nvenc", "-b:v", "3000k", "-r", "30", "-crf", "21", "-c:a", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]
        else:
            shellcmd = ["ffmpeg", "-y", "-i", source, "-vf", f"subtitles={subtitle}:force_style='Fontsize={fontsize},PrimaryColour={PrimaryColour},OutlineColour={OutlineColour},Outline=0.5,Alignment=2,MarginV=5'", "-vcodec", "h264",  "-r", "30", "-crf", "21", "-b:v", "3000k", "-acodec", "aac", "-max_muxing_queue_size", "1024", "-movflags", "faststart", "-f", "mp4", target]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("视频压制字幕错误["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

# 给视频截图
def videoShot(source, target=""):

    try:
        if target == "":
            target = f"{source}.png"
        shellcmd = ["ffmpeg", "-ss", "1", "-y", "-i", source, "-vframes", "1", target]
        ret = subprocess.run(shellcmd, stdin=None, input=None, stdout=None, stderr=None, timeout=3000, shell=False)
        if(ret.returncode != 0):
            logger.error("视频截取图片错误["+",".join(shellcmd)+"]")
            return False
        return True
    except Exception as e:
        print(e)
        return False

def timeFmtHHMMDDSSS(sec):
    hour = int(sec // (60 * 60))
    minute = int((sec - (hour * 60*60)) // 60)
    second = int(sec % 60 // 1)
    sss = int(sec * 1000 % 1000)

    return [hour, minute, second, sss]

def stimeFmtHHMMDDSSS(sec):
    result = timeFmtHHMMDDSSS(sec)
    return f"{result[0]:02d}:{result[1]:02d}:{result[2]:02d}.{result[3]}" 

# 如果判断目录存在，则删除重建
def rmFile(file):
    if isExists := os.path.exists(file):
        os.remove(file)

sconfigparser = ConfigParser()

def getConfigVal(section, item):
    # 判断是否存在节点，如果没有则读取一下配置；
    if (not sconfigparser.has_section('system')):
        sconfigparser.read(f"{getWorkDir()}/config/sys.conf")
    if (not sconfigparser.has_section(section)):
        logger.error(f"{getWorkDir()}/config/sys.conf,不存在，或者缺少配置项:{section}")
        return None
    return sconfigparser.get(section, item)
    
# 获取词性
def pos_tagging(words):
    """
    对输入的词语列表进行词性标注
    :param words: 分词后的词语列表
    :return: 包含 (词语, 词性) 的列表
    """
    # 将词语列表拼接成句子
    sentence = "".join(words)
    
    # 使用 jieba.posseg 进行词性标注
    words_with_pos = pseg.cut(sentence)
    
    # 返回 (词语, 词性) 的列表
    return [(word, pos) for word, pos in words_with_pos]

# if __name__ == "__main__" :
#     getAudioDuration("/Users/xiaobo/develop/cstd/vhuman/work/22")
if __name__ == "__main__" :    

    jfile = "/root/test/subtitle/subtitle.srt"
    vvt = "/root/test/subtitle/sub.vvt"
    target = "/root/test/subtitle/target_1080p.mp4"
    source = "/root/test/subtitle/video_1080p.mp4"
    subtitleToVvt(jfile, vvt)
    # videoAddSubtitle(source, subtitle, target)
